<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/9/28
 * Time: 15:36
 */

namespace app\web\controller;

use app\api\controller\v2\Auth;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\live\LiveAnchorInfo;
use app\common\cachemodel\zl1_relation\Zl1AstrCommunityArticle;
use app\common\cachemodel\zl1_relation\Zl1RelationAnalysisIdea;
use app\common\cachemodel\zlcr2\GuessQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\Aes;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use app\common\model\MapCollect;
use app\common\model\Recode;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsUserQuestion;
use \think\Controller;
use \think\Db;
use think\Env;
use think\Log;
use think\Exception;

class AcgDemo extends Controller
{

    protected function _initialize(): void
    {
        parent::_initialize();
        $res = Util::androidVersion('2.2.0');
        $this->assign('version', $res);
    }


    /**
     * 手机号解密测试
     * https://local-beta-wechat.goddessxzns.com/web/acg_demo/msg_code?tel=X1YWpuP9p4WSGin4idwlrQ==
     * @return \think\response\Json|void
     */
    public function msg_code()
    {
        if (Env::get('host.name') !== 'online')
        {
            $tel_param = input("tel", "");
            try
            {
                $tel = (new Aes())->decryptWithOpenssl($tel_param);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), $tel_param . ',解密失败！');
            }
            return show(config('code.success'), $tel_param . ',解密成功=' . $tel);
        }
    }

    /**
     * 准了 app全局跳转
     * @return mixed
     */
    public function test()
    {

        $m = Env::get('host.m');
        $m_zhunle = Env::get('host.m_zhunle');

        $host = Env::get('host.domain');

        $data = (new LiveAnchorInfo())
            ->alias('a')
            ->join('wechat_backup_07_18_14_43_00.live_recording_info ri', 'a.live_id=ri.live_id')
            ->group('ri.live_id')
            ->column('max(ri.id) record_id,a.name,ri.status', 'ri.live_id');

//        if (strpos($m, 'dev') || strpos($m, 'beta'))
//        {
        $headers = $this->request->header();
        $app_type = $headers['app-type'] ?? '';

        $ask = [
            'guess' => [
                'id' => 0,
            ],
            'question' => [
                'qid' => 0,
                'question' => '没有查询到',
            ],
            'comment' => [
                'id' => 0,
            ],
        ];
        try
        {
            //获取问答banner 列表，第一个猜你想问
            $ask['guess'] = (new GuessQuestion())->where(['status' => 1])->order('id', 'DESC')->field('id,question')->find();
            //查询列表的第一个问题（未登录的情况）
            $listData = (new Zlcr2UserQuestion())->getIndexList(0, 1);
            $ask['question'] = $listData['data'][0];
            //查询问题详情的讨论id
            $ask['comment'] = (new ArticleComment())->getPageCommentList(0, 4, (int)$ask['question']['qid'], 2, 1)['data'][0];
        }
        catch (Exception $e)
        {
            Log::write('所有跳转测试-问答异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }


        //v2.9.0
        $version290 = [
            'relation_research_home' => [
                'rid_self' => 0,//自己的档案
                'rid_other' => 0,//其他的档案
            ],
            'relation_research_ideal_result' => [
                'id' => 0,//关系研究所-你的理想型方案结果id
            ],
            'sign_discuss_detail' => [
                'id' => 0,//星座讨论详情id
            ],
        ];

        try
        {
            $headers = $this->request->header();

            if (isset($headers['sign']))
            {//在App里请求
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];

                //查询出用户所有的档案
                $recodes = Db::table('app_recode')->alias('r')
                    ->join('app_recode_astro ra', 'r.id=ra.rid', 'INNER')
                    ->field('r.id,r.name,r.type,r.year,r.month,r.day,r.hour,r.minute,r.timezone,birth_country,birth_province,birth_city,live_country,live_province,live_city,comments,isself,long_deg,long_min,ew,lat_deg,lat_min,ns,avatar,is_summer,uid,aid,sun,moon,merc,venu,mars,jupi,satu,non,lili,juno,asc,mc')
                    ->where(['uid' => $uid, 'status' => 1])
                    ->select();

                foreach ($recodes as $v)
                {
                    if ($v['isself'])
                    {//过滤用户自己的档案
                        $version290['relation_research_home']['rid_self'] = $v['id'];
                    } else
                    {//其他人的档案
                        $version290['relation_research_home']['rid_other'] = $v['id'];
                    }
                }

                //查询用户关系研究所-你的理想型方案结果id
                $relation_research_ideal_result_data = (new Zl1RelationAnalysisIdea())->getListPage($uid, 'id', ['status', 'create_time', 'tag_info', 'id']);
                if ($relation_research_ideal_result_data && isset($relation_research_ideal_result_data['data'][0]['id']))
                {
                    $version290['relation_research_ideal_result']['id'] = $relation_research_ideal_result_data['data'][0]['id'];
                } else
                {
                    $version290['relation_research_ideal_result']['id'] = 0;
                }

            }
        }
        catch (\Exception $e)
        {
            Log::write('所有跳转测试-2.9.0异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }
        try
        {
            //查询 星座讨论详情id
            $sign_discuss_list = (new Zl1AstrCommunityArticle())->getArticleIds([], []);
            if ($sign_discuss_list && isset($sign_discuss_list['data'][0]['id']))
            {
                $version290['sign_discuss_detail']['id'] = $sign_discuss_list['data'][0]['id'];
            } else
            {
                $version290['sign_discuss_detail']['id'] = 0;
            }
        }
        catch (\Exception $e)
        {
            Log::write('所有跳转测试-2.9.0异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
        }

        //v2.9.4 惊喜类型 1=>星座讨论 2=>占星知识 3=>心理测试 4=>名人星盘 5=>卡券
        $version294 = [
            'fortune_increase_card_detail' => [
                'id' => 0,
            ],
            'question_answer_add' => [
                'title' => urlencode("我喜欢的人喜欢我吗？"),
            ],
            'mental_test_zhunle' => [//准了自己的心理测试
                'not_test' => [//未测试
                    'sid' => 0,
                    'date' => '',
                    'id' => 0,
                ],
                'tested' => [//已测试
                    'sid' => 0,
                    'date' => '',
                    'id' => 0,
                ],
            ],
            'star_synastry' => [
                'id' => 0,//zl2_user_surprise_record 表里的type=4的sid数据
            ],
        ];
        try
        {
            $headers = $this->request->header();

            //test
//            $headers['sign'] = 'test';

            if (isset($headers['sign']))
            {//在App里请求
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];

                //test
//                $uid = 12345883;

                //查询用户最近的 转运卡片
                $version294['fortune_increase_card_detail'] = Db::table("zl2_fortune_tarot_card")
                    ->field('id')
                    ->where(['uid' => $uid])
                    ->order(['id' => 'desc'])
                    ->limit(1)
                    ->find();

                //查询用户的心理测试-未测试的惊喜id
                $data_not_test = Db::table("zl2_user_surprise_record")
                    ->field('sid,date,id')
                    ->where(['uid' => $uid, 'type' => 3, 'option' => ''])
                    ->order(['id' => 'desc'])
                    ->limit(1)
                    ->find();
                if ($data_not_test)
                {
                    $version294['mental_test_zhunle']['not_test']['sid'] = $data_not_test['sid'];
                    $version294['mental_test_zhunle']['not_test']['date'] = $data_not_test['date'];
                    $version294['mental_test_zhunle']['not_test']['id'] = $data_not_test['id'];
                }

                //查询用户的心理测试-已测试的惊喜id
                $data_tested = Db::table("zl2_user_surprise_record")
                    ->field('sid,date,id')
                    ->where(['uid' => $uid, 'type' => 3])
                    ->where('option', '<>', "")
                    ->order(['id' => 'desc'])
                    ->limit(1)
                    ->find();

                if ($data_tested)
                {
                    $version294['mental_test_zhunle']['tested']['sid'] = $data_tested['sid'];
                    $version294['mental_test_zhunle']['tested']['date'] = $data_tested['date'];
                    $version294['mental_test_zhunle']['tested']['id'] = $data_tested['id'];
                }

                //查询用户的明星合盘
                $data_star_synastry = Db::table("zl2_user_surprise_record")
                    ->field('sid')
                    ->where(['uid' => $uid, 'type' => 4])
                    ->order(['id' => 'desc'])
                    ->limit(1)
                    ->find();

                if ($data_star_synastry)
                {
                    $version294['star_synastry']['id'] = $data_star_synastry['sid'];
                }

            }
        }
        catch (\Exception $e)
        {
            Log::write('所有跳转测试-2.9.4异常：' . $e->getMessage() . '，失败行数：' . $e->getLine(), 'error');
        }

        //Applink的域名
        $env = Env::get('host.name');
        $app_link_pre = $env . '-';
        if ($env === 'online')
        {
            $app_link_pre = '';
        }

        //分享数据（用于测试微信网页打开App）
//        $signPackage = (new Jssdk())->getSignPackage(Env::get('host.domain') . '/web/acg_demo/test');
        $signPackage = (new Jssdk())->getSignPackage();

        //<a href="{$m}/meditate_list?type=0&need_auth=0" target="_blank">冥想课程栏目列表页（推荐）</a><br>
        //<a href="{$m}/meditate_list?type=1&need_auth=0" target="_blank">冥想课程栏目列表页（专题）</a><br>
        //<a href="{$m}/meditate_my_list?type=0&need_auth=2" target="_blank">我的冥想列表页（我的冥想）</a><br>
        //<a href="{$m}/meditate_my_list?type=1&need_auth=2" target="_blank">我的冥想列表页（冥想记录）</a><br>

        //临时测试m站
        $version2104 = [
            'm' => [
                ['title' => '冥想课程栏目列表页（推荐）', 'link' => 'meditate_list?type=0&need_auth=0'],
                ['title' => '冥想课程栏目列表页（专题）', 'link' => 'meditate_list?type=1&need_auth=0'],
                ['title' => '我的冥想列表页（我的冥想）', 'link' => 'meditate_my_list?type=0&need_auth=2'],
                ['title' => '我的冥想列表页（冥想记录）', 'link' => 'meditate_my_list?type=1&need_auth=2'],
                ['title' => '合盘首页', 'link' => 'composite?need_auth=1'],
            ],
            'm_zhunle' => [],
        ];


        //m站新域名数据
        $version2104['m_zhunle'] = $version2104['m'];
        foreach ($version2104['m_zhunle'] as $key => $value)
        {
            $version2104['m_zhunle'][$key]['link'] = '?app=zhunle&target=local&link=' . urlencode($value['link']);
        }


        //2.10.5版本
        $version2105 = [
            'm' => [
                ['title' => '准币充值', 'link' => 'coin_add?need_auth=2'],
                ['title' => '准币明细', 'link' => 'coin_list?need_auth=2'],
                ['title' => '钱包', 'link' => 'coin_info?need_auth=2'],
            ],
            'm_zhunle' => [],
        ];

        //2.10.5版本-m站新域名
        $version2105['m_zhunle'] = $version2105['m'];
        foreach ($version2105['m_zhunle'] as $key => $value)
        {
            $version2105['m_zhunle'][$key]['link'] = '?app=zhunle&target=local&link=' . urlencode($value['link']);
        }

        return $this->fetch('test', [
            'data' => $data,
            'app_type' => $app_type,
            'm' => $m,
            'm_zhunle' => $m_zhunle,
            'host' => $host,
            'ask' => $ask,//问答增加的参数
            'date_now' => date("Y-m-d"),//当前日期，当天运势日记添加（fortune_day_note_add）需要
            'version290' => $version290,
            'version294' => $version294,
            'version2104' => $version2104,
            'version2105' => $version2105,
            'app_link_pre' => $app_link_pre,
            'signPackage' => $signPackage,
        ]);
    }

    /**
     * 准有好事 app全局跳转
     * @return mixed
     */
    public function test_zyhs()
    {
        $m = Env::get('host.m_zyhs');
        $host = Env::get('host.domain');

        $headers = $this->request->header();
        $app_type = $headers['app-type'] ?? '';
        $env = Env::get('host.name');

        $uid = '';//uid为空说明不在App里面/没有登录
        if (isset($headers['access-token']) && $headers['access-token'] !== '')
        {//在App里请求
            $auth = new ZyhsAuth();
            $auth->checkRequestAuth();
            $uid = $auth->user['id'];
        }

        //v1.0.0 版本数据
        $version100 = [
            'astrologer_home_id' => '',//占星师id【占星师个人主页（未登录也能跳转）】
            'chat_id' => '',//占星师id【跳转到聊天页面（必须登录）】
            'chat_order_detail_id' => '',//咨询id【跳转到连线咨询详情（必须登录）】
            'question_id' => '',//问题ID【问答-问题详情（未登录也能跳转）】
        ];
        try
        {
            //咨询id【跳转到连线咨询详情】
            if ($uid === '')
            {
                $version100['chat_id'] = '跳转失败：需要您在App里打开，并且登录';
                $version100['chat_order_detail_id'] = '跳转失败：需要您在App里打开，并且登录';
            } else
            {
                $version100['chat_id'] = 11;
                //查询列表，取第一个
                $rtc_list = (new ZyhsConsultChatRtcRecord())->userRtcChat(1, $uid);
                if (empty($rtc_list['data']))
                {
                    $version100['chat_order_detail_id'] = '跳转到指定的连线咨询详情，跳转失败：需要您有真实的连线才能跳转';
                } else
                {
                    $version100['chat_order_detail_id'] = $rtc_list['data'][0]['id'];
                }
            }

            //占星师id【占星师个人主页、跳转到聊天页面】
            $version100['astrologer_home_id'] = 11;

            //问题ID【问答-问题详情】
            $pageDataIds = (new ZyhsUserQuestion())->getQuestionTimeSortIds(1, 1);
            $question_id = array_keys($pageDataIds['data'])[0];
            $version100['question_id'] = $question_id;
        }
        catch (\Exception $e)
        {
            Log::write('所有跳转测试-1.0.0异常：' . $e->getMessage() . '，失败行数：' . $e->getLine(), 'error');
        }

        //v1.2.0 版本
        //Applink的域名
        try
        {
            $app_link_pre = $env . '-';
            if ($env === 'online')
            {
                $app_link_pre = '';
            }

            //分享数据（用于测试微信网页打开App）
            $signPackage = (new Jssdk())->getSignPackage();
        }
        catch (\Exception $e)
        {
            Log::write('所有跳转测试-v1.2.0异常：' . $e->getMessage() . '，失败行数：' . $e->getLine(), 'error');
        }


        return $this->fetch('test_zyhs', [
            'app_type' => $app_type,
            'm' => $m,
            'host' => $host,
            'date_now' => date("Y-m-d"),//当前日期，当天运势日记添加（fortune_day_note_add）需要
            'app_link_pre' => $app_link_pre,
            'signPackage' => $signPackage,
            'version100' => $version100,
        ]);
    }

    /**
     * 聊天室测试
     * @return mixed
     */
    public function websocket()
    {
        if (Env::get('host.name') !== 'online')
        {
            return $this->fetch('chat', ['websocket_gateway' => config('websocket.web_gateway')]);
        }
    }

    /**
     * 服务端发送消息测试
     * @return mixed
     */
    public function websocket2()
    {
        if (Env::get('host.name') !== 'online')
        {
            return $this->fetch('chat2', [
                'oss' => Env::get('host.photo'),
                'websocket_gateway' => config('websocket.web_gateway'),
                'h5_key_of_ws_login' => config('websocket.h5_key_of_ws_login'),
            ]);
        }
    }

    private function mall()
    {
        $data = Db::table('wechatadmin.mall_city')->where(['level' => 3])->order(['id' => 'asc'])->select();
        $temp_pid = '';
        $temp_last_item = [];
        foreach ($data as $k => $v)
        {
            if ($temp_pid)
            {
                if ($v['pid'] != $temp_pid)
                {
                    $insert_item = $temp_last_item;
                    $insert_item['id'] = $temp_last_item['id'] + 1;
                    $insert_item['name'] = '其它区县';
                    $insert_item['sname'] = '其它区';
                    $insert_item['yzcode'] = '';

                    $mername = explode(',', $temp_last_item['mername']);
                    $insert_item['mername'] = $mername[0] . ',' . $mername[1] . ',' . $mername[2] . ',其他区';

                    $insert_item['lng'] = '';
                    $insert_item['lat'] = '';
                    $insert_item['pinyin'] = 'Qitaqu';

                    Db::table('wechatadmin.mall_city')->insert($insert_item);//todo 未插入最后一条数据，因为就执行一次，所以手动插入
                }
            }
            //赋值临时pid
            $temp_pid = $v['pid'];
            $temp_last_item = $v;
        }

        return show(config('code.success'), '加载成功', $data);

    }

    // 仅作为demo使用
    private function index()
    {
        $ip = request()->ip();

        $rid = input('rid/d', 8);

        $recode = Db::table('app_recode')
            ->field('uid,name,type,year,month,day,hour,minute,timezone,long_deg,long_min,ew,lat_deg,lat_min,ns,is_summer')
            ->where('id', $rid)
            ->find();

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $utdatenow = strftime("%d.%m.%Y", $timestamp);
        $utnow = strftime("%H:%M:%S", $timestamp);

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];
        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];


        $exec_str = config('astrolog.prefix') . " -b{$utdatenow} -ut{$utnow} -p0123456789DAmHt -eswe -house{$longitude},{$latitude},p -fad -g, -head";

        exec($exec_str, $out);

        $planet1 = [];
        $planet2 = [];
        foreach ($out as $k => $o)
        {
            if ($k <= 9 || $k == 12 || $k == 27 || $k == 28)
            {
                $line = explode(',', $o);

                $key = $k;

                if ($k == 27) $key = 17;
                if ($k == 28) $key = 20;

                $planet1[$key] = $line[0] * 1;
                $planet2[$key] = $line[1] * 1;
            }
        }
        return $this->fetch('index2', [
            'planet1' => json_encode($planet1),
            'planet2' => json_encode($planet2),
            'lon' => $longitude,
        ]);
    }

    /**
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    private function point()
    {
        $type = input('get.type');// 地点类型

        $rid = input('get.rid');// 档案id

        $uid = input('get.uid');// 用户id

        $current_longitude = input('get.current_longitude');// 所在位置经纬度

        $current_latitude = input('get.current_latitude');// 所在位置经纬度

        $point_longitude = input('get.point_longitude');// 选择点的经纬度

        $point_latitude = input('get.point_latitude');// 选择点的经纬度

        $recode = (new Recode())->getRecode(['uid' => $uid, 'id' => $rid]);

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];
        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $info = [
            'type' => $type,// 1=>普通地点，2=>命运之地
            'rid' => $rid,// 档案id
            'current_longitude' => $current_longitude,// 当前所在位置经度
            'current_latitude' => $current_latitude,// 当前所在位置纬度
            'point_longitude' => $point_longitude,// 选择的点的经度
            'point_latitude' => $point_latitude,// 选择的点的纬度
            'longitude' => $longitude,// 用户出生地经度
            'latitude' => $latitude,// 用户出生地纬度
            'time' => $timestamp,// 用户出生时间
            'sex' => $recode['type'],// 档案性别
        ];

        $validate = validate('Map');

        //验证请求参数
        if (!$validate->scene('read')->check($info))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $Acg = new Acg();

//        $data = $Acg->getPointInfo($info);
        $data = $Acg->getRecommendedInfo($info);

        // 判断该地点是否被收藏
        try
        {
            $addr = MapCollect::hasWhere('map', [
                'latitude' => $point_latitude,
                'longitude' => $point_longitude,
            ])->find();

            if ($addr || !empty($addr))
            {
                $data['is_collect'] = true;
                $data['collect_id'] = $addr['id'];
            }
        }
        catch (\Exception $e)
        {
            $data['is_collect'] = false;
            $data['collect_id'] = 0;
        }

        if ($type == 2)
        {
            $data['type'] = true;
        }

        return show(config('code.success'), '加载成功', $data);
    }


    /**
     * 流式输出测试
     * https://local-beta-wechat.goddessxzns.com/web/acg_demo/stream
     * @return void
     */
    public function stream()
    {
        if (Env::get('host.name') !== 'online')
        {
            // 这行代码设置 HTTP 响应的 Content-Type 为 text/event-stream，这是服务器发送事件（SSE）的 MIME 类型。
            header('Content-Type: text/event-stream');
            // 这行代码设置 HTTP 响应的 Cache-Control 为 no-cache，告诉浏览器不要缓存此响应。
            header('Cache-Control: no-cache');
            // 这行代码设置 HTTP 响应的 Connection 为 keep-alive，保持长连接，以便服务器可以持续发送事件到客户端。
            header('Connection: keep-alive');
            header('X-Accel-Buffering: no');//这一行必须存在，否则不好使（X-Accel-Buffering 头信息设置为“no”，表示已经禁用缓冲机制，服务器会立即发送响应数据，以确保客户端能够尽早地接收到数据。而如果设置为“yes”或不设置该头信息，则表示启用缓冲机制，服务器会将响应数据写入缓冲区，然后批量发送给客户端。)

            // 输出数据
            $str = '你的本命**冥王星**落在第7宫，你在人际关系上存在一些挑战，你希望能够找到真正与你心灵相通的人，但可能由于自我保护的倾向，你在表达自己和理解他人方面遇到了困难，进而导致你与他人之间的沟通交流变得不畅，容易产生误解和冲突。你需要更加坦诚地表达自己，尝试与他人建立亲密的联系，并寻求个人需求和集体互动之间的平衡。

最后发现你的本命太阳和海王星**四分相**，你在人际关系上存在一些阻碍，这可能源自于你与他人之间存在一种难以捉摸和模糊的因素影响，导致你们之间的沟通和互动出现了不稳定的情况。建议你加强自我意识和情绪管理能力，在面对人际交往时更加自信和坚定。同时，要注意提升你的沟通技巧，包括倾听和理解他人的观点和感受，以建立更加互信和良好的**人际关系**。';
            for ($i = 0; $i < strlen($str); $i++)
            {
                echo $str[$i];
                flush();
                usleep(8000);//1 秒 = 1000000 微秒
            }
            exit;
        }
    }
}
